﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace PuzzleCoop
{
    class SpriteSheet
    {
        int nFrames; // número total de frames de cada animação
        int frameWidth;
        int interval;

        GameObject gameObject;

        int actualFrame = 10;
        double intervalAcc = 0;

        Vector2 prevPos = Vector2.Zero;

        public SpriteSheet(GameObject gameObject, int nFrames, int interval)
        {
            this.gameObject = gameObject;
            this.nFrames = nFrames;
            this.interval = interval;
            this.frameWidth = gameObject.sprite.Width / nFrames;
            gameObject.origin.X = frameWidth / 2;
            gameObject.sourceRectangle = new Rectangle(actualFrame * frameWidth, 0, frameWidth, gameObject.sprite.Height);
        }

        public void Update(GameTime gameTime)
        {
            if (gameObject.position == prevPos)
            {
                actualFrame = 0;
                intervalAcc = interval;
            }
            else
            {
                intervalAcc += gameTime.ElapsedGameTime.TotalMilliseconds;
                if (intervalAcc > interval)
                {
                    intervalAcc -= interval;
                    actualFrame++;
                    if (actualFrame >= nFrames) actualFrame = 0;
                }
            }
            gameObject.sourceRectangle.X = actualFrame * frameWidth;
            prevPos = gameObject.position;
        }
    }
}
